import { http } from "@/utils/http";
import type { HttpResponse } from "types/request";

import { URL_PREFIX } from "./constants";

export type LoginData = {
  username: string;
  password: string;
  device_info?: string;
};

export type UserAccessTokenResult = {
  access_token: string;
  token_type: string;
  expire_at: number;
};

export type CurrentUser = {
  /** 头像 */
  avatar?: string;
  /** 用户名 */
  name: string;
  /** 中文名 */
  name_cn?: string;
  /** 当前登录用户的角色 */
  roles?: string;
  /** 按钮级别权限 */
  permissions?: string;
};

/** 登录 */
export const userLoginApi = (data: LoginData) => {
  return http.request<HttpResponse<UserAccessTokenResult>>(
    "post",
    `${URL_PREFIX}/login`,
    {
      data
    },
    {
      skipAuth: true
    }
  );
};

/** 刷新 Access Token（使用 HttpOnly 刷新 Cookie） */
export const refreshAccessTokenApi = () => {
  return http.request<HttpResponse<UserAccessTokenResult>>(
    "post",
    `${URL_PREFIX}/login/token/refresh`,
    undefined,
    {
      skipAuth: true
    }
  );
};

/** 注销并撤销刷新 Cookie */
export const revokeRefreshTokenApi = () => {
  return http.request<HttpResponse<null>>(
    "post",
    `${URL_PREFIX}/login/token/revoke`,
    undefined,
    {
      skipAuth: true
    }
  );
};

/** 获取当前用户信息 */
export const getCurrentUser = () => {
  return http.request<HttpResponse<CurrentUser>>(
    "get",
    `${URL_PREFIX}/user/me`
  );
};
